﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;

namespace ECSE6770
{
    public static class StockHelper
    {
        public static IEnumerable<TickerItem> StockData()
        {
            var tickerData = ContextManager.CurrentDb.TickerItems.ToArray();
            string urlFormat = ConfigurationManager.AppSettings["StockUrlFormat"];
            string symbols = String.Join("+", tickerData.Select(t => t.Symbol));
            string data = new WebClient().DownloadString(String.Format(urlFormat, symbols));
            int i = 0;
            using (StringReader reader = new StringReader(data))
            {
                string row;
                while ((row = reader.ReadLine()) != null)
                {
                    string[] items = row.Split(',');
                    decimal value;
                    if (items.Length > 3 && Decimal.TryParse(items[3], out value))
                    {
                        tickerData[i].Value = value;
                    }
                    i++;
                }
            }

            return tickerData;
        }
    }
}